package com.cdplife.ci.modular.system.service.impl;

import cn.stylefeng.roses.core.reqres.response.SuccessResponseData;
import cn.stylefeng.roses.core.util.ToolUtil;
import cn.stylefeng.roses.kernel.model.exception.ServiceException;
import com.aliyun.oss.OSSClient;
import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.cdplife.ci.core.common.constant.Const;
import com.cdplife.ci.core.common.exception.BizExceptionEnum;
import com.cdplife.ci.core.common.ftp.FtpOss;
import com.cdplife.ci.core.common.ftp.UploadResult;
import com.cdplife.ci.core.shiro.ShiroKit;
import com.cdplife.ci.modular.system.model.Accessory;
import com.cdplife.ci.modular.system.dao.AccessoryMapper;
import com.cdplife.ci.modular.system.model.Insurance;
import com.cdplife.ci.modular.system.model.Policy;
import com.cdplife.ci.modular.system.service.IAccessoryService;
import com.baomidou.mybatisplus.service.impl.ServiceImpl;
import com.cdplife.ci.modular.system.service.IInsuranceService;
import com.cdplife.ci.modular.system.service.IPolicyService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.File;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static com.cdplife.ci.modular.system.service.impl.PolicyPlanServiceImpl.SUCCESS_TIP;

/**
 * <p>
 * 附件路径表 服务实现类
 * </p>
 *
 * @author jers
 * @since 2018-11-07
 */
@Service
public class AccessoryServiceImpl extends ServiceImpl<AccessoryMapper, Accessory> implements IAccessoryService {

    @Autowired
    private IPolicyService policyService;
    @Autowired
    private IInsuranceService insuranceService;

    /**
     * @brief 增加附件
     * @param uploadResult 上传结果
     * @param accessoryTable 附件所属表名
     * @param refId 所属表的记录主键ID
     * @param accessoryType 附件类型 对应config表类型
     * @return
     */
    @Transactional
    public Object saveAccessory(UploadResult uploadResult,String accessoryTable,Integer refId,Integer accessoryType){
        if(!uploadResult.success){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        if(ToolUtil.isOneEmpty(accessoryTable,accessoryType)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        OSSClient ossClient = FtpOss.createOSSClient();
        try {
            Accessory accessory = new Accessory();
            accessory.setAccessoryTable(accessoryTable);
            accessory.setLastModifiedBy(ShiroKit.getUser().getId().toString());
            accessory.setCreatedBy(ShiroKit.getUser().getId().toString());
            accessory.setAccessoryType(accessoryType);
            accessory.setRefId(refId);
            accessory.setThumbPath(uploadResult.getThumbPath());
            accessory.setFilePath(uploadResult.getFilePath());
            accessory.setFileSize(uploadResult.getFileSize());
            accessory.setFileName(uploadResult.getFileName());
            accessory.insert();
            //发送到oss
            FtpOss.uploadFile(ossClient, uploadResult.getFilePath(), uploadResult.getBasePath()+ Const.TMP_DIR + uploadResult.getFilePath());
            //删除临时文件
            File oldFile = new File(uploadResult.getBasePath()+ Const.TMP_DIR + uploadResult.getFilePath());
            oldFile.delete();
            //增加对应表的附件数量
            addTableAccessoryNum(accessoryTable,refId);
            Map<String,String> data = new HashMap<>();
            data.put("id",accessory.getId().toString());
            data.put("fileName",accessory.getFileName());
            data.put("fileUrl",uploadResult.getFilePathUrl());
            if(uploadResult.getThumbPath() != null ){
                FtpOss.uploadFile(ossClient, uploadResult.getThumbPath(), uploadResult.getBasePath()+ Const.TMP_DIR + uploadResult.getThumbPath());
                //删除临时文件
                File oldFile2 = new File(uploadResult.getBasePath()+ Const.TMP_DIR + uploadResult.getThumbPath());
                oldFile2.delete();
                data.put("fileThumbUrl",uploadResult.getThumbPathUrl());
            }else{
                data.put("fileThumbUrl","");
            }
            return new SuccessResponseData(data);
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }finally {
            FtpOss.disconnect(ossClient);
        }
    }

    /**
     * @brief 增加附件数量
     * @param accessoryTable
     * @param refId
     */
    private void addTableAccessoryNum(String accessoryTable,Integer refId){
        if("policy".equals(accessoryTable)){
            Policy policy = policyService.selectById(refId);
            policy.setAccessoryNum(policy.getAccessoryNum() + 1);
            policy.updateById();
        }else if("insurance".equals(accessoryTable)){
            Insurance insurance = insuranceService.selectById(refId);
            insurance.setAccessoryNum(insurance.getAccessoryNum() + 1);
            insurance.updateById();
        }
    }
    /**
     * @brief 增加附件数量
     * @param accessoryTable
     * @param refId
     */
    private void reduceTableAccessoryNum(String accessoryTable,Integer refId){
        if("policy".equals(accessoryTable)){
            Policy policy = policyService.selectById(refId);
            if(policy.getAccessoryNum() > 0){
                policy.setAccessoryNum(policy.getAccessoryNum() - 1);
                policy.updateById();
            }
        }else if("insurance".equals(accessoryTable)){
            Insurance insurance = insuranceService.selectById(refId);
            if(insurance.getAccessoryNum() > 0){
                insurance.setAccessoryNum(insurance.getAccessoryNum() - 1);
                insurance.updateById();
            }
        }
    }

    /**
     * @brief 删除附件
     * @param accessoryId 附件ID
     * @return
     */
    @Transactional
    public Object deleteAccessory(Integer accessoryId){
        if(ToolUtil.isOneEmpty(accessoryId)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        try {
            Accessory accessory = this.baseMapper.selectById(accessoryId);
            accessory.setLastModifiedBy(ShiroKit.getUser().getId().toString());
            accessory.setIsDel(1);
            accessory.updateById();
            //减少对应表的附件数量
            reduceTableAccessoryNum(accessory.getAccessoryTable(),accessory.getRefId());
            return SUCCESS_TIP;
        }catch (Exception e){
            e.printStackTrace();
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }

    }


    /**
     * @brief 获取附件信息
     * @param accessoryTable
     * @param refId
     * @param accessoryType
     * @return
     */
    public List<Accessory> getAccessoryList(String accessoryTable, Integer refId, Integer accessoryType){
        if(ToolUtil.isOneEmpty(accessoryTable,refId,accessoryType)){
            return null;
        }
        try {
            Wrapper<Accessory> wrapper = new EntityWrapper<Accessory>();
            wrapper = wrapper.eq("is_del",0)
                    .eq("ref_id",refId)
                    .eq("accessory_table",accessoryTable)
                    .eq("accessory_type",accessoryType);
            List<Accessory> accessorys = this.baseMapper.selectList(wrapper);
            //设置OSS图片连接
            for(Accessory accessory : accessorys){
                accessory.setFilePath(FtpOss.getImgUrl(accessory.getFilePath()));
                if(accessory.getThumbPath() != null){
                    accessory.setThumbPath(FtpOss.getImgUrl(accessory.getThumbPath()));
                }
            }
            return accessorys;
        }catch (Exception e){
            e.printStackTrace();
            return null;
        }
    }
}
